package com.hmdp.utils;

import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


public class SimpleRedisLock implements ILock{
    private final String KEY_PREFIX="lock";
    private final String name;
    private StringRedisTemplate stringRedisTemplate;
    private String lock;
    private final String ID_PREFIX= UUID.randomUUID()+"-";
    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT=new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    @Override
    public boolean tryLock(long timeoutSec) {
        long threadId = Thread.currentThread().getId();
        Boolean success = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + name, threadId + ID_PREFIX, timeoutSec, TimeUnit.MINUTES);
        return Boolean.TRUE.equals(success);//防止success为null，拆箱的时候出现空指针异常
    }

    @Override
    public void unLock(){
        stringRedisTemplate.execute(
                UNLOCK_SCRIPT,
                Collections.singletonList(KEY_PREFIX+name),
                ID_PREFIX+Thread.currentThread().getId());

    }
//    @Override
//    public void unLock() {
//        long threadId = Thread.currentThread().getId();
//        String id = stringRedisTemplate.opsForValue().get(lock + name);
//        //判断当前锁是不是当前线程的，防止误删
//        if (Objects.equals(id, threadId + ID_PREFIX)){
//            stringRedisTemplate.delete(lock+name);
//        }
//    }
}
